package cn.wolfcode.crm.exception;

import cn.wolfcode.crm.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ControllerAdvice
public class CRMExceptionHandler {
	/**
	 * 捕获运行过程中出现的运行时的异常
	 *
	 * @param ex
	 * @param model
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@ExceptionHandler(RuntimeException.class)
	public String handleException(Exception ex, Model model, HandlerMethod handler, HttpServletResponse response) throws ServletException, IOException {
		//输出异常信息
		ex.printStackTrace();
		//判断当前方式是不是ajax请求响应的方法(判断是否有ResponseBody注解)
		if (handler.hasMethodAnnotation(ResponseBody.class)) {
			//如果是返回jsonResult
			JsonResult json = new JsonResult(false, "操作失败请联系管理员");
			//设置数据为json,指定编码集为utf-8
			response.setContentType("application/json; charset=utf-8");
			//使用response对象输出数据(格式为json字符串)
			response.getWriter().print(JSON.toJSONString(json));
			return null;
		}
		//如果不是返回错误视图
		model.addAttribute("ex", ex);
		return "common/error"; //返回错误视图
	}
	@ExceptionHandler(UnauthorizedException.class)
	public String handleUnauthorizedException(Exception ex, Model model, HandlerMethod handler, HttpServletResponse response) throws ServletException, IOException {
		//输出异常信息
		ex.printStackTrace();
		//判断当前方式是不是ajax请求响应的方法(判断是否有ResponseBody注解)
		if (handler.hasMethodAnnotation(ResponseBody.class)) {
			//如果是返回jsonResult
			JsonResult json = new JsonResult(false, "操作失败请联系管理员");
			//设置数据为json,指定编码集为utf-8
			response.setContentType("application/json; charset=utf-8");
			//使用response对象输出数据(格式为json字符串)
			response.getWriter().print(JSON.toJSONString(json));
			return null;
		}
		//如果不是返回错误视图
		model.addAttribute("ex", ex);
		return "common/nopermission"; //返回错误视图
	}
}
